//
//  SimilarViewController.swift
//  ShopIOS
//
//  Created by Apple on 2019/8/2.
//  Copyright © 2019 Apple. All rights reserved.
//

import UIKit

class SimilarViewController: UIViewController {
    
    @IBOutlet weak var collectionview: UICollectionView!
    @IBOutlet weak var uv_back: UIView!
    
    var productId=""
    var categoryId=""
    
    var pageNo=1
    var productList=[SimilarProduct]()
    init(productId:String,categoryId:String) {
        super.init(nibName: nil, bundle: nil)
        self.productId=productId
        self.categoryId=categoryId
        loaddata()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        uv_back.addOnClickListener(target: self, action: #selector(back))
        
        collectionview.register(UINib(nibName: "SimilarCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "re")
        collectionview.collectionViewLayout=UICollectionViewFlowLayout()
        collectionview.backgroundColor="#f2f2f2".color()
        
        //refresh
        let header = TTRefreshHeader.init(refreshingBlock: {[weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = 1
            strongSelf.collectionview.mj_footer.state = .idle
            strongSelf.collectionview.mj_header.endRefreshing()
            strongSelf.loaddata()
        })
        
        collectionview.mj_header = header;
        
        let footer = TTRefreshFooter  {  [weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = strongSelf.pageNo + 1
            strongSelf.loaddata();
        }
        
        collectionview.mj_footer = footer
        collectionview.mj_footer.isHidden = true

        // Do any additional setup after loading the view.
    }
    @objc func back(){
        self.navigationController?.popViewController(animated: true)
    }
    func loaddata(){
        let d = [
                    "productId":productId,
                    "categoryId":categoryId
                ] as [String : String]
        AlamofireHelper.get(url: GetHotProduct, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if ss.pageNo == 1{ ss.productList.removeAll()}
            
            if ss.collectionview.mj_header.isRefreshing(){
                ss.collectionview.mj_header.endRefreshing()
            }else if ss.collectionview.mj_footer.isRefreshing() {
                ss.collectionview.mj_footer.endRefreshing()
                
            }
            let similarResult=SimilarResult.init(json: res)
            
            
            if similarResult.Product.count>0 {
                if ss.collectionview.mj_footer.isHidden && similarResult.Product.count > 0 {
                    ss.collectionview.mj_footer.isHidden = false
                }
                ss.productList.insert(contentsOf: similarResult.Product, at: ss.productList.count)
                if ss.productList.count < 20 {
                    ss.collectionview.mj_footer.state = .noMoreData
                }
            }else {
                ss.collectionview.mj_footer.state = .noMoreData
            }
            ss.collectionview.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
            if ss.collectionview.mj_header.isRefreshing(){ss.collectionview.mj_header.endRefreshing()}
            else if ss.collectionview.mj_footer.isRefreshing() {ss.collectionview.mj_footer.endRefreshing()}
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
extension SimilarViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return productList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "re", for: indexPath)as!SimilarCollectionViewCell
        let item=productList[indexPath.row]
        if (item.imagePath != nil){
            cell.iv_img.setImage(path: URL.init(string: "http://mall.xigyu.com/\(item.imagePath!)")!)
        }
        cell.lb_name.text=item.productName
        cell.lb_price.text="￥\(item.minSalePrice)"
        cell.layer.cornerRadius=5
//        cell.border(color: .black, width: 1, type: UIBorderSideType.UIBorderSideTypeAll, cornerRadius: 5)
        cell.backgroundColor = .white
//        cell.layer.shadowColor = UIColor.black.cgColor
//        cell.layer.shadowOffset = CGSize(width: 5, height: 5)
//        cell.layer.shadowRadius = 2.5
//        cell.layer.shadowOpacity = 0.9
        
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let padding: CGFloat =  10
        let collectionViewSize = collectionView.frame.size.width - 3*padding
        
        return CGSize(width: collectionViewSize/2, height: 50+17*3+collectionViewSize/2-10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.navigationController?.pushViewController(ProductDetailViewController(pid: "\(productList[indexPath.row].id)"), animated: true)
    }
}
